package threading;

public class ThreadDemo3_19_BiteHomework {
    public static void main(String[] args) throws InterruptedException {
        //创建三个锁对象
        Object locker1 = new Object();
        Object locker2 = new Object();
        Object locker3 = new Object();

        //需要用到等待 wait notify
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized(locker1) {
                    try {
                        locker1.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("A");
                //打印完A 之后唤醒 B，唤醒B之后 又再次进入循环，又再次wait状态
                synchronized(locker2) {
                    locker2.notify();
                }
            }
        },"A");

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {

                synchronized(locker2) {
                    try {
                        locker2.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print("B");

                //打印完B之后  唤醒 C
                synchronized(locker3) {
                    locker3.notify();
                }
            }
        },"B");

        Thread t3 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized(locker3) {
                    try {
                        locker3.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("C");

                //在这里需要重新唤醒 A
                synchronized(locker1) {
                    locker1.notify();
                }
            }
        },"C");


        t1.start();
        t2.start();
        t3.start();

        //注意这里需要先让 t1 t2 t3 线程执行完之后再 唤醒t1 线程，不然会notify空打一炮
        Thread.sleep(1000);

       //在此之前都是wait的状态，需要先唤醒 t1 线程
       synchronized(locker1) {
           locker1.notify();
       }

    }
}
